package org.dennisit.elastic.process;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.dennisit.entity.DataFactory;
import org.dennisit.entity.Medicine;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
/**
 * Created by xiangchao on 2016/7/14.
 */
public class ElasticSearchHandler {

     Client client = TransportClient.builder().build()
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

    public ElasticSearchHandler() throws UnknownHostException {
    }


    /**
     * 建立索引,索引建立好之后,会在elasticsearch-0.20.6\data\elasticsearch\nodes\0创建所以你看
     *
     * @param indexName 为索引库名，一个es集群中可以有多个索引库。 名称必须为小写
     * @param indexType Type为索引类型，是用来区分同索引库下不同类型的数据的，一个索引库下可以有多个索引类型。
     * @param jsondata  json格式的数据集合
     * @return
     */
    public void createIndexResponse(String indexname, String type, List<String> jsondata) {
        //创建索引库 需要注意的是.setRefresh(true)这里一定要设置,否则第一次建立索引查找不到数据
        IndexRequestBuilder requestBuilder = client.prepareIndex(indexname, type).setRefresh(true);
        for (int i = 0; i < jsondata.size(); i++) {
             requestBuilder.setSource(jsondata.get(i)).execute().actionGet();
        }

    }

    /**
     * 执行搜索
     *
     * @param queryBuilder
     * @param indexname
     * @param type
     * @return
     */
    public List<Medicine> searcher( BoolQueryBuilder qb, String indexname, String type) {
        List<Medicine> list = new ArrayList<Medicine>();
        SearchResponse searchResponse = client.prepareSearch(indexname).setTypes(type)
                .setQuery(qb)
                .execute()
                .actionGet();
         SearchHits hits = searchResponse.getHits();
         System.out.println("查询到记录数=" + hits.getTotalHits());
        SearchHits searchHists = searchResponse.getHits();

        for (SearchHit hit : searchHists) {
            Integer id = (Integer) hit.getSource().get("id");
            String name = (String) hit.getSource().get("name");
            String function = (String) hit.getSource().get("funciton");
            list.add(new Medicine(id, name, function));
        }

        return list;
    }


    public static void main(String[] args) throws UnknownHostException {
        ElasticSearchHandler esHandler = new ElasticSearchHandler();
        List<String> jsondata = DataFactory.getInitJsonData();
        String name1 = "xc";
        String type = "test";
        esHandler.createIndexResponse(name1,type,jsondata);
        //查询条件

        // SearchRequestBuilder searchRequestBuilder = client.prepareSearch(indexname);
        // searchRequestBuilder.setQuery(QueryBuilders.fieldMaskingSpanQuery("name"));
     /*  QueryBuilder queryBuilder = QueryBuilders.boolQuery()
          .must(QueryBuilders.termQuery("id", "5"));*/
        BoolQueryBuilder qb = QueryBuilders.boolQuery().must(new QueryStringQueryBuilder("头痛").field("function"));
       List<Medicine> result = esHandler.searcher(qb, name1, type);
        for(int i=0; i<result.size(); i++){
            Medicine medicine = result.get(i);
            System.out.println("(" + medicine.getId() + ")药品名称:" +medicine.getName() + "\t\t" + medicine.getFunction());

        }
    }
}

